<?php


namespace App\Console\Commands\ES;

use Elasticsearch\ClientBuilder;
use Illuminate\Console\Command;

class ESBaseCommand extends Command
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'es:import';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Import data to index';

    /**
     * @var $index
     */
    protected $index;

    /**
     * @var $model
     */
    protected $model;

    /**
     * @var $host
     */
    protected $host;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->host = config('scout.elasticsearch.hosts');
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->warn('Please mapping your model first, @example: php artisan mapping:user');
        return 0;
    }

    /**
     * import data to index
     * @return mixed
     */
    public function import()
    {
        $host = $this->host;
        $index = $this->index;
        $model = new $this->model;
        $model::getInstance()->chunk(1000, function ($query) use($index, $host) {
            $bulk = [];
            foreach ($query as $datum) {
                $item = $datum->toSearchableArray();
                $bulk[] = ['index' => [
                    '_index' => $index,
                    '_id' => $item['id'] ?? uniqid(),
                ]];
                $bulk[] = $item;
            }
            $client = ClientBuilder::create()->setHosts($host)->build();
            $client->bulk(['body' => $bulk]);
        });
        return 0;
    }

}
